package per.ethan.springboot.basic.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import per.ethan.springboot.basic.property.StateEnum;

import java.time.LocalDateTime;

/**
 * @author Ethan
 * @date 2020/06/09 10:22
 */
@Component
public class MetaHandler implements MetaObjectHandler {

    /**
     * 通用字段：创建时间
     */
    private static final String CREATE_TIME = "createTime";

    /**
     * 通用字段：更新时间
     */
    private static final String UPDATE_TIME = "updateTime";

    /**
     * 通用字段：已删除
     */
    private static final String STATE = "state";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 判断是否有相关字段
        boolean hasCreateTime = metaObject.hasSetter(CREATE_TIME);
        boolean hasUpdateTime = metaObject.hasSetter(UPDATE_TIME);
        boolean hasDeleted = metaObject.hasSetter(STATE);

        // 有字段则自动填充
        if (hasCreateTime) {
            strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (hasUpdateTime) {
            strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
        if (hasDeleted) {
            strictInsertFill(metaObject, STATE, Integer.class, StateEnum.NORMAL.getCode());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object val = getFieldValByName(UPDATE_TIME, metaObject);
        // 没有自定义值时才更新字段
        if (null == val) {
            strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        }
    }
}
